package com.ideas.impl.mianshi;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lijian.wu
 * @Date 2024/4/17 21:48
 * 两个线程，一个打印123，一个打印ABC，交替输出1A2B3C
 */
public class NumberLetterPrinter {

    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    public static void main(String[] args) {

        Thread thread1 = new Thread(new PrintNumbers());
        Thread thread2 = new Thread(new PrintLetters());

        thread1.start();
        thread2.start();
    }

    private static class PrintNumbers implements Runnable {

        @Override
        public void run() {
            for (int i = 1; i <= 3; i++) {
                lock.lock();
                try{
                    System.out.println(i);
                    //唤醒打印字母的线程
                    condition.signal();
                    if (i < 3){
                        condition.await();
                    }
                }catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    private static class PrintLetters implements Runnable {

        @Override
        public void run() {
            for (char i = 'A'; i <= 'C'; i++) {
                lock.lock();
                try{
                    System.out.println(i);
                    //唤醒打印数字的线程
                    condition.signal();
                    if (i < 'C'){
                        condition.await();
                    }
                }catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
